package model

import (
	"fmt"
	"gitee.com/liumou_site/gcs"
	"gitee.com/liumou_site/logger"
	"io"
	"net"
	"net/http"
	"regexp"
	"runtime"
	"strings"
)

func (i *IP) GetIp() {
	i.getIp6()
	i.getIp4()
}
func (i *IP) getIp4() {
	i.Ip4Exists = false
	if strings.EqualFold(i.IpType, "A") || strings.EqualFold(i.IpType, "ALL") {
		if i.Debug {
			logger.Debug("正在获取ipv4地址")
		}
	} else {
		return
	}
	i.SetV4 = true
	i.httpGetIP4("https://ip.liumou.site/api")
	if i.Err != nil {
		logger.Error("获取ipv4地址失败: ", i.Err)
		return
	}
	if i.Debug {
		logger.Debug("获取ipv4地址成功", i.Ip)
	}
}

// getIp6 获取ipv6
func (i *IP) getIp6() {
	i.Ip6Exists = false
	if strings.EqualFold(i.IpType, "AAAA") || strings.EqualFold(i.IpType, "ALL") {
		if i.Debug {
			logger.Debug("正在获取ipv6地址")
		}
	} else {
		return
	}
	i.SetV6 = true
	v6, err := GetIPv6AddressesStartingWith24()
	if err == nil {
		i.Ip = v6[0]
		i.IP6 = i.Ip
		i.Err = nil
		i.Ip6Exists = true
		if i.Debug {
			logger.Debug("通过正则匹配IPV6地址成功", i.Ip)
		}
		return
	}

	pre := "inet"
	c := gcs.NewShell()
	OsType := runtime.GOOS
	if strings.EqualFold(OsType, "linux") {
		c.RunShell("ip -6 a")
	} else {
		i.Err = fmt.Errorf("本地获取IPV6地址方法目前仅支持Linux系统")
		return
	}
	if c.Err == nil {
		if i.Debug {
			logger.Debug("命令执行成功,正在匹配IP地址")
		}
		i.Out = c.Strings
		i.Pre = pre
		i.linuxIPv6Address()
		return
	}
	i.Ip = ""
	i.Err = fmt.Errorf("无法获取IPV6地址")
}

func (i *IP) httpGetIP4(url string) {
	resp, err := http.Get(url)
	if err != nil {
		i.Err = err
		return
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			logger.Error(err.Error())
			return
		}
	}(resp.Body)

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		i.Err = err
		return
	}

	// 移除IPv6地址后的换行符
	ipStr := strings.TrimSpace(string(body))
	ip := net.ParseIP(ipStr)

	// 检查是否是IPv6地址
	if !strings.Contains(ipStr, ".") {
		i.Err = fmt.Errorf("not an IPv6 address")
		return
	}
	i.Ip = ip.String()
	i.Err = nil
	i.IP4 = i.Ip
	i.Ip4Exists = true
}

// Ipv6PatternStr 匹配IPV6地址
// 参数data 匹配的字符串
// 返回值 匹配的IPV6地址数组
func Ipv6PatternStr(data string) string {
	//var ips []net.IP
	// 使用正则表达式匹配以240开头，可能包含::的IPv6地址部分
	// 注意：这个正则表达式不会确保整个IPv6地址的合法性，只是匹配部分字符串
	ipv6Pattern := `240[0-9a-fA-F]+(:[0-9a-fA-F]+)*(::([0-9a-fA-F]+:)*[0-9a-fA-F]+)?`
	re := regexp.MustCompile(ipv6Pattern)

	// 查找所有匹配的IPv6地址部分
	matches := re.FindAllString(data, -1)

	// 输出结果
	fmt.Println("Matched IPv6 Address Parts:")
	for _, match := range matches {
		ip := net.ParseIP(match)
		if ip != nil {
			fmt.Println("add: ", ip.String())
			return match
			//ips = append(ips, ip)
		}
	}
	return ""
	//return ips
}
func (i *IP) linuxIPv6Address() {
	if i.Debug {
		logger.Debug("匹配数据如下")
		fmt.Println(i.Out)
		fmt.Println(i.Pre)
	}
	i.Ip = Ipv6PatternStr(i.Out)
	if len(i.Ip) >= 6 {
		fmt.Println("IP: ", i.Ip)
		i.IP6 = i.Ip
		i.Err = nil
		i.Ip6Exists = true
		if i.Debug {
			logger.Debug("本地正则匹配IPV6地址成功", i.Ip)
		}
		return
	}
	logger.Warn("本地正则匹配IPV6地址失败")
	i.Ip = ""
	i.Err = fmt.Errorf("无法获取")
}
